<template>
  <div>
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item
        :label="item.remark"
        :prop="item.fieldAlias"
        v-for="item in searchFieldList"
        :key="item.fieldId"
      >
        <el-select
          v-model="queryParams[item.fieldAlias]"
          placeholder="请选择"
          v-if="item.dictionaryInfo"
        >
          <el-option
            v-for="dict in item.dictionaryInfo"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          ></el-option>
        </el-select>
        <el-input
          v-model="queryParams[item.fieldAlias]"
          :placeholder="'请输入' + item.remark"
          clearable
          @keyup.enter="handleQuery"
          v-else-if="item.selectType == 'EQUAL' || item.selectType == 'LIKE'"
        />
        <!-- <el-input-number
                v-model="queryParams[item.fieldAlias]"
                :placeholder="'请输入' + item.remark"
                :min="1"
                clearable
                @keyup.enter="handleQuery"
                v-else-if="item.selectType == 'GREATER_THAN' || item.selectType == 'LESS_THAN'"
              /> -->
        <el-date-picker
          v-model="queryParams[item.fieldAlias]"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[
            new Date(2000, 1, 1, 0, 0, 0),
            new Date(2000, 1, 1, 23, 59, 59),
          ]"
          v-else-if="item.selectType == 'DATE'"
        ></el-date-picker>
        <el-date-picker
          v-model="queryParams[item.fieldAlias]"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="datetimerange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[
            new Date(2000, 1, 1, 0, 0, 0),
            new Date(2000, 1, 1, 23, 59, 59),
          ]"
          v-else-if="item.selectType == 'DATETIME'"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-show="modelInfo && modelInfo.isAdd == '1'"
          >新增</el-button
        >
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-show="modelInfo && modelInfo.isExport == '1'"
        >导出</el-button>
      </el-col>

      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="queryModelDataList">
      <el-table-column
        :prop="item.fieldAlias"
        :label="item.remark"
        v-for="item in queryFieldList"
        :key="item.fieldId"
      >
        <template #default="scope" v-if="item.isPicture && item.isPicture == '1'">
          <el-image
            v-if="JSON.parse(scope.row[item.fieldAlias])"
            style="width: 100px; height: 100px"
            :src="JSON.parse(scope.row[item.fieldAlias])[0].url"
            :zoom-rate="1.2"
            :max-scale="7"
            :min-scale="0.2"
            :preview-src-list="handlePreviewSrcList(JSON.parse(scope.row[item.fieldAlias]))"
            :initial-index="4"
            fit="cover"
            :preview-teleported="true"
          />
        </template>
        <template #default="scope" v-else-if="item.dictionaryInfo">
          <div
            v-for="dictionary in item.dictionaryInfo"
            :key="dictionary.value"
          >
            <p v-if="dictionary.value == scope.row[item.fieldAlias]">
              {{ dictionary.label }}
            </p>
          </div>
        </template>
        <template #default="scope" v-else>
          {{ scope.row[item.fieldAlias] }}
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="150"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            v-show="modelInfo.isUpdate == '1'"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            >修改</el-button
          >
          <el-button
            link
            type="primary"
            v-show="modelInfo.isDelete == '1'"
            icon="Delete"
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
    
    <!-- 添加或修改模型对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" :fullscreen="true" append-to-body>
      <v-form-render :form-json="formJson" :form-data="formData" :option-data="optionData" ref="vFormRef">
      </v-form-render>
      <el-tabs v-show="sonModel" v-model="activeName">
        <el-tab-pane :label="item.model.modelName" :name="item.model.modelName" v-for="item in sonModelList" :key="item.model.modelId">
          <LowcodeTable ref="lowcodeTableRef" style="padding-bottom: 10px"></LowcodeTable>
        </el-tab-pane>
      </el-tabs>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>
   
  <script setup name="lowcodeTable">
import { selectListByModel, addOrUpdateModelRow, deleteModelRow, getModelSon } from "@/api/lowcode/model";
import VFormRender from '@/components/form-render/index'
import LowcodeTable from "@/components/LowcodeTable/index.vue"

const { proxy } = getCurrentInstance();

const loading = ref(true);
const showSearch = ref(false);
const total = ref(0);
const modelInfo = ref(null);
const queryFieldList = ref([]);
const searchFieldList = ref([]);
const queryModelDataList = ref([]);
const parentModelField = ref(null)
const parentRowInfo = ref(null)
const title = ref('')
const open = ref(false)
const buttonLoading = ref(false)

const formJson = ref({"widgetList":[],"formConfig":{"modelName":"formData","refName":"vForm","rulesName":"rules","labelWidth":80,"labelPosition":"left","size":"","labelAlign":"label-left-align","cssCode":"","customClass":"","functions":"","layoutType":"PC","jsonVersion":3,"onFormCreated":"","onFormMounted":"","onFormDataChange":"","onFormValidate":""}})
const formData = ref({})
const optionData = ref({})
const vFormRef = ref(null)

const sonModel = ref(false)
const sonModelList = ref([])
const activeName = ref('')
const lowcodeTableRef = ref(null)

const modelRowInfo = ref(null)

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
  },
});

const { queryParams, form } = toRefs(data);

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  // proxy.$refs.menuTreeRef.setCurrentKey(null);
  handleQuery();
}

// 初始化列表
function initTable(data, parentDataInfo){
  modelInfo.value = data.model;
  queryFieldList.value = data.queryFieldList;
  if(data.searchFieldList){
    showSearch.value = true
  }
  searchFieldList.value = data.searchFieldList;
  parentModelField.value = data.parentModelField
  parentRowInfo.value = parentDataInfo
  getList()
}

// 列表搜索
function getList() {
  // 子表数据查询
  if(parentModelField.value && parentRowInfo.value){
    queryParams.value[parentModelField.value.fieldAlias] = parentRowInfo.value[parentModelField.value.parentModelFieldAlias]
  }
  selectListByModel({
    modelId: modelInfo.value.modelId,
    pageQuery: {
      pageNum: queryParams.value.pageNum,
      pageSize: queryParams.value.pageSize,
    },
    params: queryParams.value,
  }).then((response) => {
    queryModelDataList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 新增 */
function handleAdd() {
  modelRowInfo.value = null
  sonModel.value = false
  sonModelList.value = []
  title.value = '新增' + modelInfo.value.modelName
  formJson.value = JSON.parse(modelInfo.value.modelJson)
  formData.value = {}
  optionData.value = {}
  setTimeout(() => {
    vFormRef.value.resetForm()
  }, 0);
  open.value = true
}

/** 修改 */
async function handleUpdate(row) {
  const response = await getModelSon(modelInfo.value.modelId);
  if(response.data && response.data.length > 0){
    sonModel.value = true
    activeName.value = response.data[0].model.modelName
    sonModelList.value = response.data
  }
  
  modelRowInfo.value = row
  title.value = '修改' + modelInfo.value.modelName
  formJson.value = JSON.parse(modelInfo.value.modelJson)
  optionData.value = {}
  setTimeout(() => {
    for(let i = 0; i < sonModelList.value.length; i++){
      lowcodeTableRef.value[i].initTable(sonModelList.value[i], modelRowInfo.value)
    }
    vFormRef.value.setFormData(row)
  }, 0);
  open.value = true
}

/** 删除 */
function handleDelete(row) {
  proxy.$modal.confirm('是否确认删除数据项？').then(function() {
    loading.value = true;
    return deleteModelRow({
      modelId: modelInfo.value.modelId,
      rowInfo: row
    });
  }).then(() => {
    loading.value = true;
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  }).finally(() => {
    loading.value = false;
  });
}

/** 确定 */
function submitForm(){
  buttonLoading.value = true
  setTimeout(() => {
    vFormRef.value.getFormData().then(formData => {
      if(parentModelField.value && parentRowInfo.value){
        formData[parentModelField.value.fieldAlias] = parentRowInfo.value[parentModelField.value.parentModelFieldAlias]
      }
      // Form Validation OK
      addOrUpdateModelRow({
        modelId: modelInfo.value.modelId,
        data: formData,
        rowInfo: modelRowInfo.value
      }).then(response => {
        proxy.$modal.msgSuccess("保存成功");
        getList();
        open.value = false
      })
    }).catch(error => {
      // Form Validation failed
      // proxy.$modal.msgError(error)
    }).finally(() => {
      buttonLoading.value = false;
    });
  }, 0);
}

/** 导出excel */
function handleExport(){
  proxy.download("lowcode/model/exportByModel/" + modelInfo.value.modelId, {
    ...queryParams.value,
  },`${modelInfo.value.modelName}_${new Date().getTime()}.xlsx`);
}

/** 取消 */
function cancel(){
  open.value = false
}

/** 获取图片预览列表 */
function handlePreviewSrcList(fileContent){
  var srcList = []
  for(let index in fileContent){
    srcList.push(fileContent[index].url)
  }
  return srcList
}

defineExpose({
  initTable
})
</script>
   